<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<%@ page import="org.ifilm.model.User,org.ifilm.util.GeneralConstants"%>
<%@ page import="org.ifilm.model.Project"%>
<%@ page import="java.util.List"%>
<%@ page import="org.ifilm.controller.ProjectController"%>

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Project Detail</title>
		
		<link rel="icon" type="image/png" href="/film/img/favicon.ico">
		<link href="/film/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen" />
		<script src="/film/js/jquery.js"></script>
		<script src="/film/bootstrap/js/bootstrap.min.js"></script>
		
		<style>
			body {
				padding-top: 60px;
				/* 60px to make the container go all the way to the bottom of the topbar */
			}
			.number {
				width : 100px;
			}
			.long-text {
				width : 350px;
			}
			#dummy-placeholder {
				height : 100px;
			}
			.star-box-giga-star {
				background-position: -180px -71px;
				width: 66px;
				height: 66px;
				line-height: 66px;
				display: inline-block;
				text-align: center;
				vertical-align: middle;
				font-size: 15px;
				font-weight: bold;
				color: black;
				font-family: tahoma;
				float: left;
				padding-right: 5px;
			}
			
			.titlePageSprite {
				background-image: url(/film/img/titlePageSprite.png);
				display: inline-block;
				margin-left: 60px;
				vertical-align: middle;
			}
			
			.rating {
				width: 200px;
				unicode-bidi: bidi-override;
				direction: rtl;
				text-align: center;
			}
			
			.rating>span {
				display: inline-block;
				position: relative;
				width: 1.1em;
			}
			
			.rating>span:hover,.rating>span:hover ~ span {
				color: transparent;
			}
			
			.rating>span:hover:before,.rating>span:hover ~ span:before {
				content: "\2605";
				position: absolute;
				left: 0;
				color: gold;
			}
			.table td {
				vertical-align: middle;
			}
		</style>
	</head>
	
	<body>
		<jsp:include page="navigationBar.jsp"/>	
	
		<div class="container">
			<div class="content-container">			
				<c:if test="${user.id == project.creator.id}">
					<a class="pull-right" href="/film/project/editProject.do?projectId=${project.id}">Edit Project</a>
				</c:if>			
				<table class="table">					
					<tr>
						<td><c:if test="${project.thumbnailUrl != null}">
								<img style="width: 200px; height: 200px;" class="media-object" src="/film/photo/getPhoto.do?fileName=${project.thumbnailUrl}">
							</c:if> <c:if test="${project.thumbnailUrl == null}">
								<img class="media-object" src="http://placehold.it/200x200">
							</c:if>
							<div class="rating">
								<c:forEach var="i" begin="${rate + 1}" end="5">
									<span>☆</span>
								</c:forEach>
								<c:forEach var="i" begin="1" end="${rate}">
									<span style="color: red;">☆</span>
								</c:forEach>
							</div>
	
							<div class="titlePageSprite star-box-giga-star">${project.averageRate}</div>
						</td>
						<td width="70%">
							<table class="table">
								<tr>
									<td width="40%"><h1 id="title">${project.projectName}</h1>
										<a href='/film/user/getUser.do?userId=${project.creator.id}' class="navbar-link"><h5>${project.creator.name} ${project.creator.surname}</h5></a>
									<td></td>
								</tr>
								
								<tr>
									<td><a><h6>Country:</h6></a>${project.country}</td>
									<td><a><h6>City:</h6></a>${project.city}</td>
								</tr>
								
								<tr>
									<td><a><h6>Estimated Start Date:</h6></a>${project.startDate}</td>
									<td><a><h6>Estimated Release Date:</h6></a>${project.releaseDate}</td>
								</tr>
								<tr>
									<td><a><h6>Language:</h6></a>${project.language}</td>
									<td><a><h6>Subject:</h6></a>${project.subject}</td>
								</tr>
							</table>
						</td>
					</tr>
					<tr>
						<td colspan="3">
							<h5>Detailed Description:</h5> ${project.description}
						</td>
					</tr>				
				</table>

				<c:if test="${user.id == project.creator.id}">
					<a href="/film/notice/editPostings.do?projectId=${project.id}" role="button" class="btn pull-right">Edit Postings</a>
				</c:if>	

				<c:if test="${user.id == project.creator.id}">	
					<a href="#myModal" role="button" class="btn pull-right" data-toggle="modal">Add posting</a>
					<jsp:include page="jobPostings.jsp"/>
				</c:if>	

				<ul class="nav nav-tabs">
					<li class="active"><a href="#jobs" data-toggle="tab">Job Postings related to this project</a></li>
					<li><a href="#eqps" data-toggle="tab">Equipments needed for this project</a></li>
					
				</ul>
				<div class="tab-content">
					<div class="tab-pane active" id="jobs">
						<table class="table" border=0>
							<c:forEach var="jobPosting" items="${project.jobPostings}">
								<tr>
									<td width=66% border=0>
										<div id="physicalproperties" class="accordion-group">
											<div class="accordion-heading">
												<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#${jobPosting.id}">${jobPosting.type}</a>
											</div>	
											<div id="${jobPosting.id}" class="accordion-body collapse">
												<div class="accordion-inner">
													<table width=100%>
														<c:set var="frontCam" value="${jobPosting.type == 'actor' or jobPosting.type == 'actress' or jobPosting.type == 'dublour'}"/>
														<c:if test="${frontCam == true}">
															<tr>
																<td width=66%>Role Description:</td>
																<td>
																	${jobPosting.description}
																</td>
															</tr>
												 			<tr>
																<td width=66%>Height:</td>
																<td>
																	${jobPosting.minHeight} - ${jobPosting.maxHeight} cm
																</td>
															</tr>
															<tr>
																<td width=66%>Weight:</td>
																<td>
																	${jobPosting.minWeight} - ${jobPosting.maxWeight} kg
																</td>
															</tr>
															<tr>
																<td width=66%>Age:</td>
																<td>
																	${jobPosting.minAge} - ${jobPosting.maxAge} kg
																</td>
															</tr>
															<tr>
																<td width=66%>Hair Color:</td>
																<td>
																	${jobPosting.hairColor}
																</td>
															</tr>
															<tr>
																<td width=66%>Eye Color:</td>
																<td>
																	${jobPosting.eyeColor}
																</td>
															</tr>
															<tr>
																<td width=66%>Additional Physical Description:</td>
																<td>
																	${jobPosting.physicalDescription}
																</td>
															</tr>
															<tr>
																<td width=66%>Qualifications:</td>
																<td>
																	${jobPosting.qualifications}
																</td>
															</tr>
												 		</c:if>
												 		<c:if test="${frontCam == false}">
												 			<tr>
																<td width=66%>Job Description:</td>
																<td>
																	${jobPosting.description}
																</td>
															</tr>
												 			<tr>
																<td width=66%>Qualifications:</td>
																<td>
																	${jobPosting.qualifications}
																</td>
															</tr>
														</c:if>
													</table>
												</div>
											</div>
										</div>
									</td>
									<td>
										${jobPosting.totalAccepted}/${jobPosting.totalNeeded}
										<c:if test="${jobPosting.totalAccepted < jobPosting.totalNeeded and user.id != project.creator.id}">
								 			<button class="btn applyButton" postingId="${jobPosting.id}" style="float:right">Apply for this job</button>
								 		</c:if>							
									</td>
								</tr>
							</c:forEach>							
						</table>
					</div>
					<div class="tab-pane" id="eqps">
						<table class="table">
							<c:forEach var="eqpPosting" items="${project.equipmentPostings}">
								<tr>
								<td width=66% border=0>
										<div id="physicalproperties" class="accordion-group">
											<div class="accordion-heading">
												<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#${eqpPosting.id}">${eqpPosting.description} </a>
											</div>	
												<div id="${eqpPosting.id}" class="accordion-body collapse">
													<div class="accordion-inner">
														<table width=100%>															
												 			<tr>
																<td width=66%>Specification:</td>
																<td>
																	${eqpPosting.specifications}
																</td>
															</tr>														
													</table>
												</div>
											</div>
										</div>
									</td>
									<td>
										${eqpPosting.totalFound}/${eqpPosting.totalNeeded}
										<c:if test="${eqpPosting.totalFound < eqpPosting.totalNeeded and user.id == project.creator.id}">
								 			<button class="btn offerButton" postingId="${eqpPosting.id}" style="float:right">Offer this equipment</button>
								 		</c:if>
									</td>
								</tr>								
							</c:forEach>							
						</table>						
					</div>					
					<div class="commentBox">
						<c:if test="${user.thumbnailUrl != null}">
							<img id="avatar" style="width:60px;height:60px;" src="/film/photo/getPhoto.do?fileName=${user.thumbnailUrl}">
						</c:if>
						<c:if test="${user.thumbnailUrl == null}">
							<img id="avatar" style="width:60px;height:60px;" src="/film/img/noavatar.png">
						</c:if>
						<input id="commentText" style="width:80%; vertical-align:bottom;" placeholder="Leave a message..."/>
					</div>
					<br/>
					
					<div class=comments>
						<h5>Comments</h5>
						<c:if test="${comments == null}">
							No comments yet
						</c:if>
						
						<c:forEach var="comment" items="${comments}">
							<div data-role="post-content" class="post-content ">
								<c:if test="${comment.commentor.thumbnailUrl != null}">
									<a href="/film/user/getUser.do?userId=${comment.commentor.id}">
										<img style="width:36px;height:36px;" src="/film/photo/getPhoto.do?fileName=${comment.commentor.thumbnailUrl}">
									</a>
								</c:if>
								<c:if test="${comment.commentor.thumbnailUrl == null}">
									<a href="/film/user/getUser.do?userId=${comment.commentor.id}">
										<img style="width:36px;height:36px;" src="/film/img/noavatar.png">
									</a>
								</c:if>
								
								<div class="post-body" style="width:900px;float:right">
									<a href="/film/user/getUser.do?userId=${comment.commentor.id}">${comment.commentor.name} ${comment.commentor.surname}</a>
									<span class="bullet" aria-hidden="true">•</span>
									<fmt:formatDate pattern="yyyy-MM-dd HH:mm" value="${comment.creationTime}" />
									<p>${comment.comment}</p>
								</div>
							</div>
							<br/>
						</c:forEach>
					</div>
				</div>
			</div>
		</div>
	</body>
	
	<script>
		$(function() {
			$('#myTab a:last').tab('show');
	
			$(".rating span").click(function(e) {
				$(this).css({
					"color" : "red"
				});
				var siblingsBefore = $(this).nextAll();
				siblingsBefore.css({
					"color" : "red"
				});

				var siblingsAfter = $(this).prevAll();
				siblingsAfter.css({
					"color" : ""
				});

				var rate = siblingsBefore.length + 1;

				$.ajax("/film/project/rate.do?projectId=" + <%=request.getParameter("pid")%> + "&rate=" + rate).done(function(data) {
					if (data && data.rate) {
						$(".titlePageSprite").html(data.rate);
					}
				});
			});
		});
		var userIds = ['<%=GeneralConstants.jobPostingActor%>',
		               '<%=GeneralConstants.jobPostingActress%>',
		               '<%=GeneralConstants.jobPostingDublour%>', 
		               '<%=GeneralConstants.jobPostingProducer%>', 
		               '<%=GeneralConstants.jobPostingSupervisor%>', 
		               '<%=GeneralConstants.jobPostingProductionManager%>', 
		               '<%=GeneralConstants.jobPostingProductionCoordinator%>', 
		               '<%=GeneralConstants.jobPostingDirectorOfPhotography%>', 
		               '<%=GeneralConstants.jobPostingCameraman%>', 
		               '<%=GeneralConstants.jobPostingCostumeDesigner%>', 
		               '<%=GeneralConstants.jobPostingMakeupArtist%>', 
		               '<%=GeneralConstants.jobPostingHairDresser%>', 
		               '<%=GeneralConstants.jobPostingArtDirector%>', 
		               '<%=GeneralConstants.jobPostingSetDecorator%>', 
		               '<%=GeneralConstants.jobPostingConstructionCoordinator%>', 
		               '<%=GeneralConstants.jobPostingSoundMixer%>',
		               '<%=GeneralConstants.jobPostingBoomOperator%>',
		               '<%=GeneralConstants.jobPostingKeyGrip%>',
		               '<%=GeneralConstants.jobPostingEditor%>',
		               '<%=GeneralConstants.jobPostingColorist%>',
		               '<%=GeneralConstants.jobPostingOther%>'
		               ];
		
		var equipmentIds = ['<%=GeneralConstants.equipmentPosting%>'];
		
		$(".applyButton").click(function() {		
			var thisButton = $(this);
			$.ajax("/film/notice/applyJob.do?postingId=" + $(this).attr("postingId")).done(function(data) {
				thisButton.attr("disabled","disabled");
				thisButton.html("Applied...");
				console.log("Your application is successful.");
			});
		});
		
		$(".offerButton").click(function() {		
			var thisButton = $(this);
			$.ajax("/film/notice/offerEquipment.do?postingId=" + $(this).attr("postingId")).done(function(data) {
				thisButton.attr("disabled","disabled");
				thisButton.html("Offered...");
				console.log("Your offer is successful.");
			});
		});
		
		$(".modal .inp").blur(function() {
			var $this = $(this);
			if ($this.attr("verify") != "true") {
				$this.attr("verify", "true");
				
				var iconOk = $("<img src='/film/img/icon-ok.jpg' class='onVerifyImages'></img>");
				var iconRemove = $("<i class='icon-remove pull-right removePost onVerifyImages'></i>");
				$this.parent().append(iconRemove).append(iconOk);
			}
		});
		
		$(".removePost").live("click", function() {
			var $this = $(this);
			
			$this.prev().attr("verify", "false");
			$this.next().remove();
			$this.remove();
		});
		
		function resetModal() {
			$('.onVerifyImages').remove();
			$("#dummy-placeholder").css("display", "block");
			$(".nav.nav-tabs").css("display", "block");
			$('.tab-pane').removeClass('active');
			$('li').removeClass('active');
			$('.inp').val('');
		}
		
		postingArray = new Array();
		
		$('#addJob').click(function() {
			$.each($(".modal .tab-pane.active"), function() {
				var divId = $(this).attr("id");
				var posting = {};
				
				if ($.inArray(divId, userIds) != -1) {
					posting["post"] = "user";
					
					var anyAttributeFound = false;
					
					$.each($(".modal #" + divId + " .inp"), function() {
						anyAttributeFound = true;
						posting[$(this).attr("title")] = $(this).val();
						// to reset the input areas and remove the verified icons
						$(this).attr("verify", "false");
					});
					
					if (anyAttributeFound) {
						posting["type"] = divId;
						postingArray.push(posting);
					}
				} else if ($.inArray(divId, equipmentIds) != -1) {
					posting["post"] = "equipment";
					
					var anyAttributeFound = false;
					
					$.each($(".modal #" + divId + " .inp"), function() {
						anyAttributeFound = true;
						posting[$(this).attr("title")] = $(this).val();
						// to reset the input areas and remove the verified icons
						$(this).attr("verify", "false");
					});
					
					if (anyAttributeFound) {
						posting["type"] = divId;
						postingArray.push(posting);
					}
				}
			});
			console.log(postingArray);
			createPostings(<%=request.getParameter("pid")%>);
			resetModal();
		});
		
		function createPostings(projectId) {
			var postingData = {};
			var hede = JSON.stringify(postingData);
			postingData["projectId"] = projectId;
			postingData["postingData"] = postingArray;
			debugger;
			$.ajax({
				url : "/film/notice/createPosting.do",
				data : {data : JSON.stringify(postingData)},
				success : function(data) {
					alert("Successful");
					postingArray = [];
				},
				error : function(data) {
					alert(data.responseText);
				}
			});
		}
		
		$('#myModal').on('hide', function() {
			resetModal();
			if(postingArray.length != 0) {
				window.location.href = "/film/project/getProject.do?pid=" + <%=request.getParameter("pid")%>;
			}		
		});
		
		$('#myModal').on('show', function() {			
			$('.model-menu').click( function() { 
				$("#dummy-placeholder").css("display", "none");
			});		
		});
		
		$("#commentText").keyup(function(event) {
			if (event.keyCode == '13') {//enter keycode
				var thisInput = $(this);
				var commentText = thisInput.val();
				$.ajax("/film/project/createProjectComment.do?commentText=" + commentText + "&projectId=" + <%=request.getParameter("pid")%>).done(function(data) {
					if (data.status == "success") {
						thisInput.val("");
						
						var div = $('<div data-role="post-content" class="post-content ">');
						
						var a = $('<a href="/film/user/getUser.do?userId=' + <%=((User)session.getAttribute("user")).getId()%> + '">');
						var img = $('<img style="width:36px;height:36px;" src="' + $("#avatar").attr("src") + '">');
						a.append(img);
						
						var postBody = $('<div class="post-body" style="width:900px;float:right">');
						var user = $('<a href="/film/user/getUser.do?userId=' + <%=((User)session.getAttribute("user")).getId()%> + '">' + 
									data.user + '</a>');
						var bulletSpan = $('<span class="bullet" aria-hidden="true"> • </span>');
						
						var date = new Date();
						
						var day = date.getDate();
						if (day < 10) {
							day = '0' + day;
						}
						
						var minute = date.getMinutes();
						if (minute < 10) {
							minute = '0' + minute;
						}
						
						date = date.getFullYear() + "-" + date.getMonth() + 1 + "-" + day + " " + date.getHours() + ":" + minute;
						
						var comment = $('<p>' + commentText + '</p>');
						
						postBody.append(user).append(bulletSpan).append(date).append(comment);
						div.append(a).append(postBody);
						$(".comments").append(div).append("<br>");
					}
				});
            }
		});
	</script>
	
	<script src="/film/js/commonScripts.js"></script>
</html>